package entityData

import (
	"gitee.com/fierce_wolf/go-fox-edge-common/commSql"
	"gitee.com/fierce_wolf/go-next-entity/nextEntity"
)

type conf struct {
}

func (e *conf) QueryEntityById(id int64) (*nextEntity.ConfEntity, error) {
	entity, err := commSql.QueryEntityById(nextEntity.Type.ConfEntity.Type(), id)
	if err != nil {
		return nil, err
	}
	return entity.(*nextEntity.ConfEntity), nil
}

func (e *conf) QueryRecordByKey(confName string) (*nextEntity.ConfEntity, error) {
	sql := "SELECT * FROM tb_conf  WHERE conf_name = '" + confName + "'"
	list, err := commSql.Query(nextEntity.Type.ConfEntity.Type(), sql)
	if err != nil {
		return nil, err
	}
	if len(list) == 0 {
		return nil, nil
	}

	return list[0].(*nextEntity.ConfEntity), nil
}

func (e *conf) QueryEntityByKey(confName string) (*nextEntity.ConfEntity, error) {
	entity, err := e.QueryRecordByKey(confName)
	if err != nil {
		return nil, err
	}
	if entity == nil {
		entity = nextEntity.Type.ConfEntity.NewEntity().(*nextEntity.ConfEntity)
		entity.Name = confName
	}

	return entity, nil
}

func (e *conf) SaveEntity(confName string, data map[string]interface{}) error {
	exist, err := e.QueryRecordByKey(confName)
	if err != nil {
		return err
	}

	if exist == nil {
		entity := nextEntity.Type.ConfEntity.NewEntity().(*nextEntity.ConfEntity)
		entity.Name = confName
		entity.Data = data
		return commSql.InsertEntity(entity)
	} else {
		exist.Data = data
		return commSql.UpdateEntityById(exist)
	}
}
